// Copyright 2009 The Go Example Authors. All rights reserved.
// Use of this source code is governed by a BSD-style
// license that can be found in the LICENSE file.


package main

import (
	"fmt"
	"xml"
	"os"
	"strings"
)

//define a person info type
type Person struct {
	Name string
	Age  int
	Sex  string
}

func (p *Person) String() string {
	var content string
	content = "Name:\t" + p.Name
	content += "\nAge: \t" + fmt.Sprint(p.Age)
	content += "\nSex:\t" + p.Sex
	return content
}


type Persons struct {
	XMLName xml.Name "Persons"
	Person  []Person
}


type A2 struct {
	XMLName xml.Name "a"
	XY      string
	XX      string
}

//
const _Xa = `
<?xml version="1.0" encoding="UTF-8"?>
<a>
  <xy>foo</xy>
  <xx>bar</xx>
</a>`


func main() {
	//define filename
	var fileName string = "data/person.xml"
	//Open File 
	//打开文件
	fn, err := os.Open(fileName, os.O_RDONLY, 0444)

	if err != nil {
		// when can't open file ,the program exit
		//打开文件失败时退出
		fmt.Print("can't open file")
		os.Exit(1)
	}

	//Close File 
	//关闭文件
	defer fn.Close()

	//read(fn)	

	read2(fn)

	//read3(fn)

	//读取并解析XML
	var a A2

	if e := xml.Unmarshal(strings.NewReader(_Xa), &a); e != nil {
		fmt.Println("Unmarshal: %s", e)
	}
	if a.XY != "" {
		fmt.Println(a.XY)
	}

	fmt.Println(a.XX)
}

//读取XML文件，并解析其内容
func read(fn *os.File) {

	var p *Persons

	err := xml.Unmarshal(fn, &p)

	if err != nil && err != os.EOF {
		fmt.Println("error %s", err)
	}

	fmt.Println(p)
}

//读取XML文件，并解析其内容
func read2(fn *os.File) {
	var content string = ""

	//读取XML文档内容
	for {
		var buff [256]byte
		i, e := fn.Read(buff[:])
		//i,e :=io.ReadFull(fn,buff[:])
		if e == nil {

		}
		if i == 0 {
			break
		}

		content = content + string(buff[0:i])

	}

	fmt.Println("XML document content:\n")
	fmt.Print(content)

	var p *Persons

	//解析XML文档
	if e := xml.Unmarshal(strings.NewReader(content), &p); e != nil && e != os.EOF {
		fmt.Println("Unmarshal: %s", e)
	}

	fmt.Println("\nPerson Record:\n")
	fmt.Println(p)
}
